package database;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import database.mysql.ConnectionMySQL;
import java.sql.*;
import java.util.Iterator;
import java.util.Map;
/**
 *
 * @author teste
 */
public class DatabaseHandler {    
    private ConnectionMySQL mysql;
    private java.sql.Connection con = null;
    
    public DatabaseHandler(ConnectionMySQL mysql){
        this.con = mysql.getConnection();
    }   

    public ResultSet getResult(String query) throws SQLException{
        ResultSet rs = null;
        
        Statement st = this.con.createStatement();
        rs = st.executeQuery(query);

        return rs;
    }
    
    public int doChange(String query) throws SQLException{
        int modifiedRows = 0;
        
        Statement st = this.con.createStatement();
        modifiedRows = st.executeUpdate(query);
        
        return modifiedRows;
    }
    
    public String retrieveFieldsValues(Map params){
        String fieldsValues = "";
        int count = 0;
        
        Iterator i = params.keySet().iterator();
        
        while (i.hasNext()){
            String key = (String) i.next();
            if(!(key.equals("insert") ||  key.equals("delete") ||  key.equals("update") ||  key.equals("listAll") || key.equals("id") || key.equals("orderBy"))){
                String value = ((String[]) params.get( key ))[ 0 ];
            
                if(count != 0) fieldsValues += ",";
                if(!this.isInt(value)) value = "\""+value+"\"";
                fieldsValues += key+"="+value;

                count++;
            }
        }
        
        return fieldsValues;
    }
 
    public boolean isInt(String value){
        try{
            Integer.parseInt(value);
            return true;
        }catch(Exception e){
            return false;
        }
    }
    
}